﻿Imports DotNetNuke
Imports DotNetNuke.Common
Imports DotNetNuke.Security
Imports DotNetNuke.Entities.Profile
Imports DotNetNuke.Entities.Users
Imports DotNetNuke.Entities.Users.UserProfile
Imports System.Web.UI
Imports Telerik.Web.UI
Imports DotNetNuke.Security.Membership
Imports DotNetNuke.Services.Mail
Imports DotNetNuke.Services.FileSystem
Imports DotNetNuke.Security.Roles

Namespace dnnWerk.Modules.Users

    Partial Class uc_Register
        Inherits UserModuleBase

        Private blnPageNeedsToPostback As Boolean = False

#Region "Event Handlers"

        Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init

            DotNetNuke.Framework.AJAX.RegisterScriptManager()

            ProcessFormTemplate(plhRegister, Template_UserRegistration(CurrentLocale), Nothing, blnPageNeedsToPostback)

            Dim btnUpdate As Button = CType(FindControlRecursive(plhRegister, plhRegister.ID & "_" & Constants.ControlId_UpdateButton), Button)
            If Not btnUpdate Is Nothing Then

                AddHandler btnUpdate.Click, AddressOf btnUpdate_Click

                If blnPageNeedsToPostback Then
                    DotNetNuke.Framework.AJAX.RegisterPostBackControl(btnUpdate)
                End If

            End If

        End Sub

        Protected Sub btnUpdate_Click(ByVal sender As Object, ByVal e As System.EventArgs)
            Register()
        End Sub

#End Region

#Region "Private Methods"

        Private Sub Register()


            pnlSuccess.Visible = False
            pnlError.Visible = False

            Dim strMessage As String = ""

            Dim blnUpdateUsername As Boolean = False
            Dim blnUpdateFirstname As Boolean = False
            Dim blnUpdateLastname As Boolean = False
            Dim blnUpdateDisplayname As Boolean = False
            Dim blnUpdatePassword As Boolean = False
            Dim blnUpdateEmail As Boolean = False

            Dim txtUsername As TextBox = CType(FindControlRecursive(plhRegister, plhRegister.ID & "_" & Constants.ControlId_Username), TextBox)
            blnUpdateUsername = (Not txtUsername Is Nothing)

            If blnUpdateUsername Then
                If Not IsValidUserAttribute(Constants.User_Username, plhRegister) Then
                    strMessage += "Error"
                    AddErrorIndicator(Constants.User_Username, plhRegister)
                Else
                    RemoveErrorIndicator(Constants.User_Username, plhRegister, True)
                End If
            End If

            Dim txtEmail As TextBox = CType(FindControlRecursive(plhRegister, plhRegister.ID & "_" & Constants.ControlId_Email), TextBox)
            blnUpdateEmail = (Not txtEmail Is Nothing)

            If blnUpdateEmail Then
                If Not IsValidUserAttribute(Constants.User_Email, plhRegister) Then
                    strMessage += "Error"
                    AddErrorIndicator(Constants.User_Email, plhRegister)
                Else
                    RemoveErrorIndicator(Constants.User_Email, plhRegister, True)
                End If
            End If

            Dim txtPassword As TextBox = CType(FindControlRecursive(plhRegister, plhRegister.ID & "_" & Constants.ControlId_Password1), TextBox)
            Dim txtPassword2 As TextBox = CType(FindControlRecursive(plhRegister, plhRegister.ID & "_" & Constants.ControlId_Password2), TextBox)
            blnUpdatePassword = (Not txtPassword Is Nothing AndAlso Not txtPassword2 Is Nothing)

            If blnUpdatePassword Then
                If txtPassword.Text = "" AndAlso txtPassword2.Text = "" Then
                    blnUpdatePassword = False
                End If
            End If

            If blnUpdatePassword Then
                If Not IsValidUserAttribute(Constants.User_Password1, plhRegister) Then
                    strMessage += "Error"
                    AddErrorIndicator(Constants.User_Password1, plhRegister)
                Else
                    RemoveErrorIndicator(Constants.User_Password1, plhRegister, True)
                End If
                If Not IsValidUserAttribute(Constants.User_Password2, plhRegister) Then
                    strMessage += "Error"
                    AddErrorIndicator(Constants.User_Password2, plhRegister)
                Else
                    RemoveErrorIndicator(Constants.User_Password2, plhRegister, True)
                End If
            End If

            Dim txtFirstName As TextBox = CType(FindControlRecursive(plhRegister, plhRegister.ID & "_" & Constants.ControlId_Firstname), TextBox)
            blnUpdateFirstname = (Not txtFirstName Is Nothing)

            If blnUpdateFirstname Then
                If Not IsValidUserAttribute(Constants.User_Firstname, plhRegister) Then
                    strMessage += "Error"
                    AddErrorIndicator(Constants.User_Firstname, plhRegister)
                Else
                    RemoveErrorIndicator(Constants.User_Firstname, plhRegister, True)
                End If
            End If

            Dim txtLastName As TextBox = CType(FindControlRecursive(plhRegister, plhRegister.ID & "_" & Constants.ControlId_Lastname), TextBox)
            blnUpdateLastname = (Not txtLastName Is Nothing)

            If blnUpdateLastname Then
                If Not IsValidUserAttribute(Constants.User_Lastname, plhRegister) Then
                    strMessage += "Error"
                    AddErrorIndicator(Constants.User_Lastname, plhRegister)
                Else
                    RemoveErrorIndicator(Constants.User_Lastname, plhRegister, True)
                End If
            End If

            Dim txtDisplayName As TextBox = CType(FindControlRecursive(plhRegister, plhRegister.ID & "_" & Constants.ControlId_Displayname), TextBox)
            blnUpdateDisplayname = (Not txtDisplayName Is Nothing)

            If blnUpdateDisplayname Then
                If Not IsValidUserAttribute(Constants.User_Displayname, plhRegister) Then
                    strMessage += "Error"
                    AddErrorIndicator(Constants.User_Displayname, plhRegister)
                Else
                    RemoveErrorIndicator(Constants.User_Displayname, plhRegister, True)
                End If
            End If

            For Each itemProp As String In GetPropertiesFromTempate(Template_UserRegistration(CurrentLocale))
                Try
                    Dim prop As ProfilePropertyDefinition = ProfileController.GetPropertyDefinitionByName(PortalId, itemProp.Substring(2)) 'itemprop comes in the form U:Propertyname or P:Propertyname
                    If Not prop Is Nothing Then
                        If Not IsValidProperty(Nothing, prop, plhRegister) Then
                            strMessage += "Error"
                            AddErrorIndicator(prop.PropertyDefinitionId.ToString, plhRegister)
                        Else
                            RemoveErrorIndicator(prop.PropertyDefinitionId.ToString, plhRegister, prop.Required)
                        End If
                    End If
                Catch
                End Try
            Next

            If strMessage.Length > 0 Then
                Me.pnlError.Visible = True
                Me.lblError.Text = "<ul><li>" & Localization.GetString("FillInAll", Me.SharedResourcefile) & "</li></ul>"
                Exit Sub
            End If


            Dim oUser As UserInfo = New UserInfo

            'approve membership if applicable
            If PortalSettings.UserRegistration = PortalRegistrationType.PublicRegistration Then
                oUser.Membership.Approved = True
            Else
                oUser.Membership.Approved = False
            End If

            'set defaults
            oUser.AffiliateID = Null.NullInteger
            oUser.PortalID = PortalSettings.PortalId

            oUser.IsDeleted = False
            oUser.IsSuperUser = False
            oUser.LastIPAddress = Request.UserHostAddress
            oUser.Profile = New UserProfile
            oUser.Username = ""
            oUser.DisplayName = ""
            oUser.Email = ""
            oUser.Membership.Password = ""



            'set username depending on setting
            Select Case UsernameMode
                Case UsernameUpdateMode.Email
                    If blnUpdateEmail Then
                        oUser.Username = txtEmail.Text.Trim
                    End If
                Case UsernameUpdateMode.FirstLetterLastname
                    If blnUpdateLastname AndAlso blnUpdateFirstname Then
                        oUser.Username = txtFirstName.Text.Trim.Substring(0, 1) & "." & txtLastName.Text
                    End If
                Case UsernameUpdateMode.FirstnameLastname
                    If blnUpdateLastname AndAlso blnUpdateFirstname Then
                        oUser.Username = txtFirstName.Text & "." & txtLastName.Text
                    End If
                Case UsernameUpdateMode.Lastname
                    If blnUpdateLastname Then
                        oUser.Username = txtLastName.Text
                    End If
                Case UsernameUpdateMode.UserSelect
                    If blnUpdateUsername Then
                        oUser.Username = txtUsername.Text
                    End If
            End Select

            'set displayname depending on setting
            Select Case DisplaynameMode
                Case DisplaynameUpdateMode.Email
                    If blnUpdateEmail Then
                        oUser.DisplayName = txtEmail.Text.Trim
                    End If
                Case DisplaynameUpdateMode.FirstLetterLastname
                    If blnUpdateLastname AndAlso blnUpdateFirstname Then
                        oUser.DisplayName = txtFirstName.Text.Trim.Substring(0, 1) & ". " & txtLastName.Text
                    End If
                Case DisplaynameUpdateMode.FirstnameLastname
                    If blnUpdateLastname AndAlso blnUpdateFirstname Then
                        oUser.DisplayName = txtFirstName.Text & " " & txtLastName.Text
                    Else

                    End If
                Case DisplaynameUpdateMode.Lastname
                    If blnUpdateLastname Then
                        oUser.DisplayName = txtLastName.Text
                    End If
                Case DisplaynameUpdateMode.UserSelect
                    If blnUpdateDisplayname Then
                        oUser.DisplayName = txtDisplayName.Text
                    End If
            End Select

            If blnUpdateEmail Then
                oUser.Email = txtEmail.Text
            End If

            'try updating password
            If blnUpdatePassword Then
                If txtPassword.Text = txtPassword2.Text Then
                    If UserController.ValidatePassword(txtPassword.Text) Then
                        oUser.Membership.Password = txtPassword.Text
                    Else
                        Me.pnlError.Visible = True
                        Me.lblError.Text = "<ul><li>" & Localization.GetString("InvalidPassword.Text", SharedResourcefile) & "</li></ul>"
                        Exit Sub
                    End If
                Else
                    Me.pnlError.Visible = True
                    Me.lblError.Text = "<ul><li>" & Localization.GetString("PasswordsDontMatch.Text", SharedResourcefile) & "</li></ul>"
                    Exit Sub
                End If
            Else
                'auto-generate password
                oUser.Membership.Password = UserController.GeneratePassword(7)
            End If

            If oUser.Username = "" Or oUser.Email = "" Or oUser.DisplayName = "" Or oUser.Membership.Password = "" Then
                'template must be setup up wrong
                Me.pnlError.Visible = True
                Me.lblError.Text = "<ul><li>" & String.Format(Localization.GetString("TemplateingError.Text", SharedResourcefile), PortalSettings.Email)

                If oUser.Username = "" Then
                    lblError.Text += " | Username is empty"
                End If

                If oUser.Email = "" Then
                    lblError.Text += " | E-mail is empty"
                End If

                If oUser.DisplayName = "" Then
                    lblError.Text += " | Displayname is empty"
                End If

                If oUser.Username = "" Then
                    lblError.Text += " | password is empty"
                End If

                lblError.Text += "</li></ul>"

                Exit Sub
            End If

            'set up profile
            oUser.Profile = New UserProfile
            oUser.Profile.InitialiseProfile(PortalSettings.PortalId, True)
            oUser.Profile.PreferredLocale = PortalSettings.DefaultLanguage
            oUser.Profile.PreferredTimeZone = PortalSettings.TimeZone
            'todo: create account
            Dim createStatus As UserCreateStatus = UserController.CreateUser(oUser)

            If createStatus <> UserCreateStatus.Success Then

                Select Case createStatus
                    Case UserCreateStatus.UsernameAlreadyExists
                        Select Case UsernameMode
                            Case UsernameUpdateMode.UserSelect
                                strMessage = Localization.GetString("UsernameAlreadyExists", Me.SharedResourcefile)
                            Case UsernameUpdateMode.Email
                                strMessage = Localization.GetString("DuplicateEmail", Me.SharedResourcefile)
                            Case UsernameUpdateMode.FirstnameLastname, UsernameUpdateMode.FirstLetterLastname, UsernameUpdateMode.Lastname
                                strMessage = Localization.GetString("NameAlreadyExists", Me.SharedResourcefile)
                        End Select
                    Case Else
                        strMessage = Localization.GetString("createStatus", Me.SharedResourcefile)
                End Select

                If strMessage <> "" Then
                    strMessage = "<li>" & strMessage & "</li>"
                Else
                    strMessage = "<li>" & createStatus.ToString & "</li>"
                End If

                Me.pnlError.Visible = True
                Me.lblError.Text = "<ul>" & strMessage & "</ul>"

                Exit Sub
            End If

            UpdateProfileProperties(plhRegister, oUser, GetPropertiesFromTempate(Template_UserRegistration(CurrentLocale)))

            'loop trough dynamic profile attributes and set those
            For Each itemProp As String In GetPropertiesFromTempate(Template_UserRegistration(CurrentLocale))
                Try

                    Dim prop As ProfilePropertyDefinition = ProfileController.GetPropertyDefinitionByName(PortalId, itemProp.Substring(2))
                    If Not prop Is Nothing Then

                        Dim ctl As Control = GetPropertyControl(prop, plhRegister)

                        If Not ctl Is Nothing Then

                            If TypeOf (ctl) Is Telerik.Web.UI.RadComboBox Then

                                Dim value As String = CType(ctl, Telerik.Web.UI.RadComboBox).SelectedValue.Trim

                                If prop.PropertyName.ToLower = "region" Then
                                    value = CType(ctl, Telerik.Web.UI.RadComboBox).SelectedItem.Text.Trim
                                End If
                                If prop.PropertyName.ToLower = "country" Then
                                    value = CType(ctl, Telerik.Web.UI.RadComboBox).SelectedItem.Text.Trim
                                End If

                                oUser.Profile.SetProfileProperty(prop.PropertyName, value)

                            ElseIf TypeOf (ctl) Is Telerik.Web.UI.RadDateTimePicker Then
                                oUser.Profile.SetProfileProperty(prop.PropertyName, CType(ctl, Telerik.Web.UI.RadDateTimePicker).DbSelectedDate.ToString)

                            ElseIf TypeOf (ctl) Is Telerik.Web.UI.RadTimePicker Then
                                oUser.Profile.SetProfileProperty(prop.PropertyName, CType(ctl, Telerik.Web.UI.RadTimePicker).DbSelectedDate.ToString)

                            ElseIf TypeOf (ctl) Is Telerik.Web.UI.RadDatePicker Then
                                oUser.Profile.SetProfileProperty(prop.PropertyName, CType(ctl, Telerik.Web.UI.RadDatePicker).DbSelectedDate.ToString)

                            ElseIf TypeOf (ctl) Is CheckBox Then
                                oUser.Profile.SetProfileProperty(prop.PropertyName, CType(ctl, CheckBox).Checked.ToString)

                            ElseIf TypeOf (ctl) Is TextBox Then
                                oUser.Profile.SetProfileProperty(prop.PropertyName, CType(ctl, TextBox).Text.Trim)

                            ElseIf TypeOf (ctl) Is Telerik.Web.UI.RadNumericTextBox Then
                                oUser.Profile.SetProfileProperty(prop.PropertyName, CType(ctl, Telerik.Web.UI.RadNumericTextBox).Value.ToString)

                            ElseIf TypeOf (ctl) Is DotNetNuke.Web.UI.WebControls.DnnImageEditControl Then
                                oUser.Profile.SetProfileProperty(prop.PropertyName, CType(ctl, DotNetNuke.Web.UI.WebControls.DnnImageEditControl).Value)

                            ElseIf TypeOf (ctl) Is DotNetNuke.Web.UI.WebControls.DnnFileEditControl Then
                                oUser.Profile.SetProfileProperty(prop.PropertyName, CType(ctl, DotNetNuke.Web.UI.WebControls.DnnFileEditControl).Value)

                            End If

                        End If

                    End If
                Catch
                End Try
            Next

            If blnUpdateFirstname = True Then
                oUser.Profile.FirstName = txtFirstName.Text
                oUser.FirstName = txtFirstName.Text
            Else
                If oUser.Profile.FirstName <> "" Then
                    oUser.FirstName = oUser.Profile.FirstName
                End If
            End If

            If blnUpdateLastname = True Then
                oUser.Profile.LastName = txtLastName.Text
                oUser.LastName = txtLastName.Text
            Else
                If oUser.Profile.LastName <> "" Then
                    oUser.LastName = oUser.Profile.LastName
                End If
            End If

            If oUser.Username = "" Or oUser.Email = "" Or oUser.DisplayName = "" Or oUser.Membership.Password = "" Or oUser.FirstName = "" Or oUser.LastName = "" Then
                'template must be setup up wrong
                Me.pnlError.Visible = True
                Me.lblError.Text = "<ul><li>" & String.Format(Localization.GetString("TemplateingError.Text", SharedResourcefile), PortalSettings.Email)

                If oUser.Username = "" Then
                    lblError.Text += " | Username is empty"
                End If

                If oUser.Email = "" Then
                    lblError.Text += " | E-mail is empty"
                End If

                If oUser.DisplayName = "" Then
                    lblError.Text += " | Displayname is empty"
                End If

                If oUser.Username = "" Then
                    lblError.Text += " | password is empty"
                End If


                If oUser.FirstName = "" Then
                    lblError.Text += " | Firstname is empty"
                End If

                If oUser.LastName = "" Then
                    lblError.Text += " | LastName is empty"
                End If

                lblError.Text += "</li></ul>"

                Exit Sub
            End If

            Try
                oUser.Profile.SetProfileProperty("Email", oUser.Email)
            Catch
            End Try

            'update profile
            ProfileController.UpdateUserProfile(oUser)
            UserController.UpdateUser(PortalId, oUser)


            Dim strUserBody As String = ""
            Dim strAdminBody As String = ""


            If PortalSettings.UserRegistration = PortalRegistrationType.PrivateRegistration Then

                strUserBody = Template_Email_RegisterAccount_UserPrivate(CurrentLocale)
                strAdminBody = Template_Email_RegisterAccount_Admin(PortalSettings.DefaultLanguage)

            ElseIf PortalSettings.UserRegistration = PortalRegistrationType.VerifiedRegistration Then

                strUserBody = Template_Email_RegisterAccount_UserVerified(CurrentLocale)
                If NotifyAddress <> "" Then
                    strAdminBody = Template_Email_RegisterAccount_Admin(PortalSettings.DefaultLanguage)
                End If

            Else
                If NotifyUser Then
                    strUserBody = Template_Email_RegisterAccount_User(CurrentLocale)
                End If
                If NotifyAddress <> "" Then
                    strAdminBody = Template_Email_RegisterAccount_Admin(PortalSettings.DefaultLanguage)
                End If
            End If

            If strAdminBody <> "" Then

                strAdminBody = strAdminBody.Replace("[PORTALURL]", PortalSettings.PortalAlias.HTTPAlias)
                strAdminBody = strAdminBody.Replace("[PORTALNAME]", PortalSettings.PortalName)
                strAdminBody = strAdminBody.Replace("[USERID]", oUser.UserID)
                strAdminBody = strAdminBody.Replace("[DISPLAYNAME]", oUser.DisplayName)
                strAdminBody = strAdminBody.Replace("[PASSWORD]", MembershipProvider.Instance().GetPassword(oUser, ""))
                strAdminBody = strAdminBody.Replace("[USERNAME]", oUser.Username)
                strAdminBody = strAdminBody.Replace("[FIRSTNAME]", oUser.FirstName)
                strAdminBody = strAdminBody.Replace("[LASTNAME]", oUser.LastName)
                strAdminBody = strAdminBody.Replace("[EMAIL]", oUser.Email)

                If PortalSettings.UserRegistration = PortalRegistrationType.PrivateRegistration Then
                    strAdminBody = strAdminBody.Replace("[ADMINACTION]", Localization.GetString("AuthorizeAccount.Action", SharedResourcefile))
                    strAdminBody = strAdminBody.Replace("[REGISTRATIONMODE]", Localization.GetString("RegistrationMode_Private.Text", SharedResourcefile))
                ElseIf PortalSettings.UserRegistration = PortalRegistrationType.VerifiedRegistration Then
                    strAdminBody = strAdminBody.Replace("[ADMINACTION]", Localization.GetString("VerifyAccount.Action", SharedResourcefile))
                    strAdminBody = strAdminBody.Replace("[REGISTRATIONMODE]", Localization.GetString("RegistrationMode_Verified.Text", SharedResourcefile))
                Else
                    strAdminBody = strAdminBody.Replace("[ADMINACTION]", Localization.GetString("NoAction.Action", SharedResourcefile))
                    strAdminBody = strAdminBody.Replace("[REGISTRATIONMODE]", Localization.GetString("RegistrationMode_Public.Text", SharedResourcefile))
                End If

                strAdminBody = strAdminBody.Replace("[USERURL]", NavigateURL(UsermanagementTab, "", "uid=" & oUser.UserID.ToString))

                Try
                    Services.Mail.Mail.SendMail(PortalSettings.Email, NotifyAddress, "", String.Format(Localization.GetString("NotifySubject_UserRegistered.Text", SharedResourcefile), PortalSettings.PortalName), strAdminBody, "", "HTML", "", "", "", "")
                Catch
                End Try

            End If

            If strUserBody <> "" Then

                strUserBody = strUserBody.Replace("[PORTALURL]", PortalSettings.PortalAlias.HTTPAlias)
                strUserBody = strUserBody.Replace("[PORTALNAME]", PortalSettings.PortalName)
                strUserBody = strUserBody.Replace("[USERID]", oUser.UserID)
                strUserBody = strUserBody.Replace("[DISPLAYNAME]", oUser.DisplayName)
                strUserBody = strUserBody.Replace("[PASSWORD]", MembershipProvider.Instance().GetPassword(oUser, ""))
                strUserBody = strUserBody.Replace("[USERNAME]", oUser.Username)
                strUserBody = strUserBody.Replace("[FIRSTNAME]", oUser.FirstName)
                strUserBody = strUserBody.Replace("[LASTNAME]", oUser.LastName)
                strUserBody = strUserBody.Replace("[EMAIL]", oUser.Email)
                strUserBody = strUserBody.Replace("[VERIFICATIONCODE]", PortalSettings.PortalId.ToString & "-" & oUser.UserID.ToString)

                If PortalSettings.UserTabId <> Null.NullInteger Then
                    strUserBody = strUserBody.Replace("[USERURL]", NavigateURL(PortalSettings.UserTabId))
                Else
                    strUserBody = strUserBody.Replace("[USERURL]", NavigateURL(PortalSettings.HomeTabId, "ctl=Profile"))
                End If


                Dim returnurl As String = ""
                Dim loginurl As String = ""
                Dim verificationkey As String = PortalSettings.PortalId.ToString & "-" & oUser.UserID.ToString
                If RedirectAfterVerify <> "" Then
                    returnurl = RedirectAfterVerify.Replace("http://", "").Replace(PortalSettings.PortalAlias.HTTPAlias, "")
                End If

                If PortalSettings.LoginTabId <> Null.NullInteger Then
                    If returnurl <> "" Then
                        loginurl = NavigateURL(PortalSettings.LoginTabId, "", "ReturnUrl=" & returnurl, "VerificationCode=" & verificationkey)
                    Else
                        loginurl = NavigateURL(PortalSettings.LoginTabId, "", "VerificationCode=" & verificationkey)
                    End If
                Else
                    If returnurl <> "" Then
                        loginurl = NavigateURL(PortalSettings.HomeTabId, "", "ctl=Login", "ReturnUrl=" & returnurl, "VerificationCode=" & verificationkey)
                    Else
                        loginurl = NavigateURL(PortalSettings.HomeTabId, "", "ctl=Login", "VerificationCode=" & verificationkey)
                    End If
                End If

                strUserBody = strUserBody.Replace("[VERIFYURL]", loginurl)

                Try
                    Services.Mail.Mail.SendMail(PortalSettings.Email, oUser.Email, "", String.Format(Localization.GetString("NotifySubject_UserDetails.Text", SharedResourcefile), PortalSettings.PortalName), strUserBody, "", "HTML", "", "", "", "")
                Catch
                End Try


            End If

            'add to role
            If AddToRoleOnSubmit <> Null.NullInteger Then
                Try
                    Dim rc As New Security.Roles.RoleController
                    rc.AddUserRole(PortalId, oUser.UserID, AddToRoleOnSubmit, Null.NullDate)
                Catch
                End Try
            End If

            'remove to role
            If RemoveFromRoleOnSubmit <> Null.NullInteger Then
                Try

                    Dim rc As New Security.Roles.RoleController
                    Dim r As RoleInfo = rc.GetRole(RemoveFromRoleOnSubmit, PortalId)

                    RoleController.DeleteUserRole(oUser, r, PortalSettings, False)

                Catch
                End Try
            End If


            If PortalSettings.UserRegistration = PortalRegistrationType.PublicRegistration Then

                'logon user
                Dim logonStatus As Membership.UserLoginStatus = UserLoginStatus.LOGIN_FAILURE
                UserController.UserLogin(PortalId, oUser.Username, oUser.Membership.Password, "", PortalSettings.PortalName, Request.UserHostAddress, logonStatus, True)

                'see if all worked
                If logonStatus <> UserLoginStatus.LOGIN_SUCCESS Then

                    strMessage += logonStatus.ToString
                    Me.pnlError.Visible = True
                    Me.lblError.Text = strMessage
                    Exit Sub

                End If

            End If

            lblSucess.Text = "<ul><li>" & String.Format(Localization.GetString("RegisterSuccess", SharedResourcefile), NavigateURL()) & "</li></ul>"
            pnlSuccess.Visible = True

            If Not Request.QueryString("ReturnURL") Is Nothing Then
                Response.Redirect(Request.QueryString("ReturnURL"), True)
            End If

            If RedirectAfterSubmit <> "" Then
                Response.Redirect(RedirectAfterSubmit, True)
            End If

        End Sub

#End Region

        Protected Sub ctlAjax_AjaxRequest(ByVal sender As Object, ByVal e As Telerik.Web.UI.AjaxRequestEventArgs) Handles ctlAjax.AjaxRequest

            Dim cmd As String = e.Argument.Split(Char.Parse("|"))(0)
            Dim value As String = e.Argument.Split(Char.Parse("|"))(1)

            If cmd.ToLower = "validate_username" Then

                Dim strError As String = ""
                Dim blnValid As Boolean = True

                If value.Length = 0 Then
                    blnValid = False
                    strError = Localization.GetString("InvalidUserName.Text", SharedResourcefile)
                Else
                    If Not UserController.GetUserByName(PortalId, value) Is Nothing Then
                        blnValid = False
                        strError = Localization.GetString("UsernameAlreadyExists.Text", SharedResourcefile)
                    End If
                End If

                If Not blnValid Then
                    Try
                        CType(FindControlRecursive(plhRegister, plhRegister.ID & "_RESX_USERHELP_Username"), Literal).Text = strError
                    Catch
                    End Try
                    AddErrorIndicator(Constants.User_Username, plhRegister)

                    Dim txtUsername As TextBox = CType(FindControlRecursive(plhRegister, plhRegister.ID & "_" & Constants.ControlId_Username), TextBox)
                    If Not txtUsername Is Nothing Then
                        ctlAjax.ResponseScripts.Add("focusControl('" & txtUsername.ClientID & "');")
                    End If

                Else
                    Try
                        CType(FindControlRecursive(plhRegister, plhRegister.ID & "_RESX_USERHELP_Username"), Literal).Text = Localization.GetString("UsernameIsAvailable.Text", SharedResourcefile)
                    Catch
                    End Try
                    AddSuccessIndicator(Constants.User_Username, plhRegister)

                    'focus next control
                    Dim blnUserFound As Boolean = False
                    For Each ctl As Control In plhRegister.Controls
                        Try
                            If blnUserFound Then
                                Dim strId As String = ctl.ID
                                Dim ctlIdentifier As String = plhRegister.ID & "_ctl"
                                If strId.StartsWith(ctlIdentifier) Then
                                    'must be a register control
                                    ctlAjax.ResponseScripts.Add("focusControl('" & ctl.ClientID & "');")
                                    Exit For
                                End If
                            End If
                            If ctl.ID = plhRegister.ID & "_" & Constants.ControlId_Username Then
                                blnUserFound = True
                            End If
                        Catch
                        End Try
                    Next

                End If

            End If

            If cmd.ToLower = "validate_passwordpolicy" Then

                Dim txtPassword As TextBox = CType(FindControlRecursive(plhRegister, plhRegister.ID & "_" & Constants.ControlId_Password1), TextBox)
                Dim txtPassword2 As TextBox = CType(FindControlRecursive(plhRegister, plhRegister.ID & "_" & Constants.ControlId_Password2), TextBox)

                If UserController.ValidatePassword(value) Then
                    AddSuccessIndicator(Constants.User_Password1, plhRegister)
                    CType(FindControlRecursive(plhRegister, plhRegister.ID & "_RESX_USERHELP_Password1"), Literal).Text = Localization.GetString("ValidPassword.Text", SharedResourcefile)
                    If Not txtPassword Is Nothing Then
                        txtPassword.Text = value
                        If Not txtPassword2 Is Nothing Then
                            ctlAjax.ResponseScripts.Add("focusControl('" & txtPassword2.ClientID & "');")
                        End If
                    End If
                Else
                    AddErrorIndicator(Constants.User_Password1, plhRegister)
                    CType(FindControlRecursive(plhRegister, plhRegister.ID & "_RESX_USERHELP_Password1"), Literal).Text = Localization.GetString("InvalidPassword.Text", SharedResourcefile)
                    If Not txtPassword Is Nothing Then
                        ctlAjax.ResponseScripts.Add("focusControl('" & txtPassword.ClientID & "');")
                    End If
                End If

            End If

            If cmd.ToLower = "validate_email" Then

                If IsValidEmail(value) Then

                    AddSuccessIndicator(Constants.User_Email, plhRegister)

                    'focus next control
                    Dim blnEmailFound As Boolean = False
                    For Each ctl As Control In plhRegister.Controls
                        Try
                            If blnEmailFound Then
                                Dim strId As String = ctl.ID
                                Dim ctlIdentifier As String = plhRegister.ID & "_ctl"
                                If strId.StartsWith(ctlIdentifier) Then
                                    'must be a register control
                                    ctlAjax.ResponseScripts.Add("focusControl('" & ctl.ClientID & "');")
                                    Exit For
                                End If
                            End If
                            If ctl.ID = plhRegister.ID & "_" & Constants.ControlId_Email Then
                                blnEmailFound = True
                            End If
                        Catch
                        End Try
                    Next

                Else

                    Dim txtEmail As TextBox = CType(FindControlRecursive(plhRegister, plhRegister.ID & "_" & Constants.ControlId_Email), TextBox)
                    AddErrorIndicator(Constants.User_Email, plhRegister)
                    CType(FindControlRecursive(plhRegister, plhRegister.ID & "_RESX_USERHELP_Email"), Literal).Text = Localization.GetString("InvalidEmail.Text", SharedResourcefile)
                    If Not txtEmail Is Nothing Then
                        ctlAjax.ResponseScripts.Add("focusControl('" & txtEmail.ClientID & "');")
                    End If

                End If

            End If

            If cmd.ToLower = "validate_passwords" Then

                Dim txtPassword As TextBox = CType(FindControlRecursive(plhRegister, plhRegister.ID & "_" & Constants.ControlId_Password1), TextBox)
                Dim txtPassword2 As TextBox = CType(FindControlRecursive(plhRegister, plhRegister.ID & "_" & Constants.ControlId_Password2), TextBox)

                If Not txtPassword Is Nothing AndAlso Not txtPassword2 Is Nothing Then
                    If txtPassword.Text = txtPassword2.Text Then
                        AddSuccessIndicator(Constants.User_Password2, plhRegister)
                        CType(FindControlRecursive(plhRegister, plhRegister.ID & "_RESX_USERHELP_Password2"), Literal).Text = Localization.GetString("ValidPassword.Text", SharedResourcefile)

                        'focus next control
                        Dim blnPasswordFound As Boolean = False
                        For Each ctl As Control In plhRegister.Controls
                            If blnPasswordFound Then
                                If ctl.ID.StartsWith(plhRegister.ID & "_") Then
                                    'must be a register control
                                    ctlAjax.ResponseScripts.Add("focusControl('" & ctl.ClientID & "');")
                                    Exit For
                                End If
                            End If
                            If ctl.ID = plhRegister.ID & "_" & Constants.ControlId_Password2 Then
                                blnPasswordFound = True
                            End If
                        Next

                    Else
                        AddErrorIndicator(Constants.User_Password2, plhRegister)
                        CType(FindControlRecursive(plhRegister, plhRegister.ID & "_RESX_USERHELP_Password2"), Literal).Text = Localization.GetString("PasswordsDontMatch.Text", SharedResourcefile)
                        If Not txtPassword2 Is Nothing Then
                            ctlAjax.ResponseScripts.Add("focusControl('" & txtPassword2.ClientID & "');")
                        End If
                    End If
                End If

            End If

        End Sub

        Public Function InvalidEmailString() As String
            Return Localization.GetString("InvalidPassword.Text", SharedResourcefile)
        End Function

        Public Function ValidPasswordString() As String
            Return Localization.GetString("ValidPassword.Text", SharedResourcefile)
        End Function

        Public Function InvalidPasswordString() As String
            Return Localization.GetString("InvalidPassword.Text", SharedResourcefile)
        End Function

        Public Function PasswordsDontMatchString() As String
            Return Localization.GetString("PasswordsDontMatch.Text", SharedResourcefile)
        End Function

        Public Function MinPasswordLength() As String
            Return "7"
        End Function

        Public Function ErrorImageUrl() As String
            Return (Me.ModuleDirectory & "/images/error.png").Replace("~", "")
        End Function

        Public Function AcceptImageUrl() As String
            Return (Me.ModuleDirectory & "/images/accept.png").Replace("~", "")
        End Function

        Public Function Password1Id() As String
            Dim txtPassword As TextBox = CType(FindControlRecursive(plhRegister, plhRegister.ID & "_" & Constants.ControlId_Password1), TextBox)
            If Not txtPassword Is Nothing Then
                Return txtPassword.ClientID
            End If
            Return ""
        End Function

        Protected Sub Page_PreRender(sender As Object, e As System.EventArgs) Handles Me.PreRender

            ManageRegionLabel(Me.plhRegister)

        End Sub
    End Class

End Namespace
